<template>
  <div>
    <van-button v-if="isFollowed" class="follow-btn" round size="small"
      @click="onFollow" :loading="followLoading">已关注
    </van-button>
    <van-button v-else class="follow-btn" type="info" color="#3296fa" round
      size="small" icon="plus" @click="onFollow" :loading="followLoading">关注
    </van-button>
  </div>
</template>

<script>
// 关注用户或者取消用户关注
import { addFollow, deleteFollow } from '@/api/user.js'
export default {
  name: 'guanZhu',
  data () {
    return {
      followLoading: false// 没有loading效果
    }
  },
  // 自定义 v-model 的数据名称
  model: {
    prop: 'isFollowed', // 默认是 value
    event: 'update-is_followed' // 默认是 input
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  components: {},

  computed: {},

  mounted () { },

  methods: {
    // 关注或不关注是由文章的isFollowed这个值决定的；执行时先看你关注了没，没有就执行
    // 关注的接口；有了执行取消关注的接口；
    async onFollow () { // 点击关注按钮，执行关注或取消关注
      this.followLoading = true // 展示关注按钮的 loading 状态
      try {
        if (this.isFollowed) { // 有就关注了，取消关注
          await deleteFollow(this.userId)
        } else { // 没有，就关注
          await addFollow(this.userId)
        }
        // 按钮更新视图状态
        // this.article.is_followed = !this.article.is_followed
        this.$emit('update-is_followed', !this.isFollowed)
      } catch (err) {
        let message = '操作失败，请重试！'
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
      }
      this.followLoading = false // 关闭关注按钮的 loading 状态
    }
  }
}

</script>
<style lang='less' scoped>
</style>
